<?php
/**
 * Limit
 * author: JiangJun
 * CreateTime:2021/7/26 22:04
 */

require '../vendor/autoload.php';

use Aws\DynamoDb\Exception\DynamoDbException;
use Aws\DynamoDb\Marshaler;

$sdk = new Aws\Sdk([
    'region'   => 'us-west-2',
    'version'  => 'latest'
]);

$dynamodb = $sdk->createDynamoDb();
$marshaler = new Marshaler();

$tableName = 'Movies';

$eav = $marshaler->marshalJson('
    {
        ":yyyy":1992,
        ":letter1": "A",
        ":letter2": "F"
    }
');

/**
 * 参数记忆方法：以Expression结尾的，都是指表达式
 * 含有Attribute的，都是绑定。
 * AttributeNames 是绑定的属性名，只有当使用了保留字时，才需要绑定
 * AttributeValues 是绑定的属性值 ，必须通过绑定的方式。
 */

$params = [
    'TableName' => $tableName,
    'KeyConditionExpression' =>
        '#yr = :yyyy and title between :letter1 and :letter2',
    'ExpressionAttributeNames'=> [ '#yr' => 'year' ],
    'ExpressionAttributeValues'=> $eav,
    'Limit'=>10,
];

echo "查询出92年的电影，开头字母在A-F之间，限10条 \n";

try {
    $result = $dynamodb->query($params);

    echo "Query succeeded.\n";

    foreach ($result['Items'] as $i) {
        //unmarshalItem 将结果对象转成了数组
        $movie = $marshaler->unmarshalItem($i);
        print $movie['year'] . ': ' . $movie['title'] . ' ... rating:' . $movie['info']['rating'] . PHP_EOL;
    }

} catch (DynamoDbException $e) {
    echo "Unable to query:\n";
    echo $e->getMessage() . "\n";
}